<template>
  <div  class="app-container">
    <div style="border: 1px solid; border-color: #1890ff; width:500px; height:600px;float:left">
        <ul id="treeDemo" class="ztree" @select="zTreeOnClick"></ul>
    </div>
    <div style="float:left;">
       <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="$t('上级菜单代码')" > <!-- prop对应的是rules中的值，用于输入校验  -->
          <el-input  v-model="temp.menu_code_parent" readonly/>
        </el-form-item>
        <el-form-item :label="$t('上级菜单名称')" > <!-- prop对应的是rules中的值，用于输入校验  -->
          <el-input  v-model="temp.menu_name_parent" readonly/>
        </el-form-item>
        <el-form-item :label="$t('菜单代码')"  > 
          <el-input  v-model="temp.menu_code" placeholder="请填写菜单代码" v-bind:readonly="menu_code_readonly" />
        </el-form-item>
        <el-form-item :label="$t('菜单ID')"  > 
          <el-input  v-model="temp.menu_id" readonly />
        </el-form-item>
        <el-form-item :label="$t('菜单名称')" prop="menu_name"  v-bind:readonly="menu_name_readonly"> 
          <el-input  v-model="temp.menu_name" ref="menu_name"  placeholder="请填写菜单名称" />
        </el-form-item>
        <el-form-item :label="$t('菜单地址')" prop="menu_addr" > 
          <el-input  v-model="temp.menu_addr" placeholder="请填写菜单地址" />
        </el-form-item>
        <el-form-item :label="$t('是否启用')" > 
          <el-radio-group v-model="temp.menu_enable" size="small">
            <el-radio :label=1> <!-- 这里的label指的是radio的值，注意是带冒号的 -->
                启用
            </el-radio>
            <el-radio :label=2 >
                禁用
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('菜单图标')" > 
          <el-input v-model="temp.menu_img" />
        </el-form-item>
       </el-form>

       <div slot="footer" class="form-footer">
         <el-button type="primary" @click="setType('add')">
          {{ $t('新增') }}
        </el-button>
        <el-button type="primary" @click="addOrUpdateMenu()">
          {{ $t('保存') }}
        </el-button>
        <el-button type="primary" @click="setType('delete');doDeleteMenu()">
          {{ $t('删除') }}
        </el-button>
      </div>
    </div>
  </div>
</template>
<script>
import $ from 'jquery'
import "@/libs/ztree/js/jquery.ztree.all.js"
import "@/libs/ztree/css/zTreeStyle/zTreeStyle.css"
import {doSelBean,addMenu,updateMenu,deleteMenu,genCode } from '@/api/menu'
export default{
    data(){
        return{
            setting: {
                view: {
				            selectedMulti: false
                },
                async: {
                    enable: true,
                    url: process.env.VUE_APP_BASE_API+"/menu/doSelNode?time="+new Date(),
                    autoParam:["id", "name=n", "level=lv"],
                    //id_ini,name_ini用于设置根结点,与当前用户所在行政区划相关. 如,哈尔滨市级用户,则使用   ,"id_ini":"230100000000","name_ini":"哈尔滨"
                    otherParam:{"otherParam":"zTreeAsyncTest","id_ini":"-1","name_ini":"鑫达"},
                    type:"post"
                },
               callback:{
                   onClick: this.zTreeOnClick,
                   //beforeClick: beforeClick,
                   beforeAsync: this.beforeAsync,
                   onAsyncError: this.onAsyncError,
                   onAsyncSuccess: this.onAsyncSuccess
               }
            },
            type: 'update', //当前操作类型，默认为更新
            menu_code_current : '',
            menu_name_current : '',
            menu_code_readonly : true,
            menu_name_readonly : true,
            zTree : undefined,
            nodes : undefined,
            node: {
              id : 0 ,
              name : ''
            },
            zTreeOperate :'',
            temp: {
               menu_enable:1,
               menu_img : 'user'
            },
            beanQuery: {
              menu_id: 0
            },
            genCodeParam: {
              menu_id_parent: 0,
              menu_code_parent: ''
            },
            //输入校验规则
            rules: {
                menu_name: [{ required: true, message: '菜单名必填', trigger: 'change' }],
                menu_addr: [{ required: true, message: '菜单地址必填', trigger: 'change' }]
            }
            // zNodes:[
            //     { id:"1",  pId:"0", name:"父节点1 - 展开", open:true},
			//     { id:"11", pId:"1", name:"父节点11 - 折叠"}
            // ]
        }
        
    },
    mounted(){
        //this.base_api = process.env.VUE_APP_BASE_API
        console.log("jquery object = "+$)
        //$.fn.zTree.init($("#treeDemo"), this.setting, this.zNodes).expandAll(true);
        $.fn.zTree.init($("#treeDemo"), this.setting);
        $("#refreshNode").bind("click", {type:"refresh", silent:false}, this.refreshNode);
		  	$("#refreshNodeSilent").bind("click", {type:"refresh", silent:true}, this.refreshNode);
			  $("#addNode").bind("click", {type:"add", silent:false}, this.refreshNode);
			  $("#addNodeSilent").bind("click", {type:"add", silent:true}, this.refreshNode);
        this.selectnode(0);
        //this.expandroot();
    },
    methods: {
        zTreeOnClick(event,treeId,treeNode){
            try{
              this.getMenu(treeNode.id);
            }catch(e){
              alert(e.message);
            }
        },
        beforeAsync(treeId, treeNode) {
          // className = (className === "dark" ? "":"dark");
          // showLog("[ "+getTime()+" beforeAsync ]&nbsp;&nbsp;&nbsp;&nbsp;" + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") );
          
          return true;
        },
        onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
          alert(textStatus);
          alert(XMLHttpRequest.status);
        },
        onAsyncSuccess(event, treeId, treeNode, msg){
          this.expandroot();
        },
        //可以全部展开菜单
        expandroot(){
          this.zTree = $.fn.zTree.getZTreeObj("treeDemo");
          this.nodes = this.zTree.getNodes();
          this.zTree.expandNode(this.nodes[0], true, false, true);
          this.nodes = this.nodes[0].children;
          if(this.nodes!=null ){
             this.zTree.expandNode(this.nodes[0], true, false, true);
             this.nodes = this.nodes[0].children;
             if(this.nodes!=null ){
                this.zTree.expandNode(this.nodes[0], true, false, true);
             }
          }
        },
        refreshNode(e) {
          var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
          type = e.data.type,
          silent = e.data.silent,
          nodes = zTree.getSelectedNodes();
          if (nodes.length == 0) {
            alert("请先选择一个父节点");
          }
          for (var i=0, l=nodes.length; i<l; i++) {
            zTree.reAsyncChildNodes(nodes[i], type, silent);
            if (!silent) zTree.selectNode(nodes[i]);
          }
        },
        refresh(){
          this.doupdate(this.type,this.temp.menu_code,this.temp.menu_name); 
        },
        doupdate(opt_type, nodecode, nodename){
            this.zTree = $.fn.zTree.getZTreeObj("treeDemo");
            this.nodes = this.zTree.getSelectedNodes();
            if (this.nodes.length == 0) {
              alert("请先选择一个父节点");
            }
            if(opt_type=="update"){
              for (let i=0, l=this.nodes.length; i<l; i++) {
                this.nodes[i].name = nodename ;   				
                this.zTree.updateNode(this.nodes[i]);	
              }
            }
            else if(opt_type=="add"){
                //location.reload()  //页面完全刷新，这个方案不好
                //this.zTree = $.fn.zTree.getZTreeObj("treeDemo");
                //this.nodes = this.zTree.getSelectedNodes();
                //正常可以用异步刷新处理，但不好使，原因不明
                //this.zTree.reAsyncChildNodes(this.nodes[0], "refresh");
                //这种也不行
                //this.zTree.reAsyncChildNodes(null, "refresh");
                //let par = this.nodes[0].getParentNode();
                //this.selectnode(par.id);
            }
            else if(opt_type=="delete"){
                let par = this.nodes[0].getParentNode();
                  for (let i=0, l=this.nodes.length; i<l; i++) {
                    this.zTree.removeNode(this.nodes[i]);
                }
                par.isParent = true;
                this.zTree.updateNode(par);
                //this.zTree.selectNode(par);
                this.selectnode(par.id);
            }
            //else if(opt_type=="moveup"){
            //       var preNode = nodes[0].getPreNode();
            //       zTree.moveNode(preNode, nodes[0], "prev");
            // }else if(opt_type=="moveuplevel"){
            //       var par = nodes[0].getParentNode();
            //       var par_2 = par.getParentNode();
            //       if(par_2!=null){
            //         //异步加载指定结点
            //         //zTree.reAsyncChildNodes(par_2, "refresh");
            //       }else{
            //         //重新载入树
            //         //window.location.reload();
            //       }
            //       zTree.reAsyncChildNodes(par_2, "refresh");
            // }else if(opt_type=="movedown"){
            //       var nextNode = nodes[0].getNextNode();
            //       zTree.moveNode(nextNode, nodes[0], "next");
            // }
          //alert("this is doupdate!");
        },

        selectnode(menu_id){
            this.getMenu(menu_id)
        },
	      getMenu(menu_id){
            //查询菜单  - doSelBean
            this.beanQuery.menu_id = menu_id
            doSelBean(this.beanQuery).then(response => {
                this.temp.menu_id = response.data.menu_id;
                this.temp =  response.data;
                // if(this.temp.menu_img==null || this.temp.menu_img ==''){
                //      this.temp.menu_img = 'user';
                // }
                this.menu_code_current = this.temp.menu_code;
                this.menu_name_current = this.temp.menu_name;
                //alert(this.temp.menu_enable);
                //this.temp.menu_enable = '1'
            })
        },
        addOrUpdateMenu(){
            if(this.type=='add'){
                this.temp.menu_parent = this.temp.menu_id;
                this.temp.menu_order = this.temp.menu_code ;
                this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                  addMenu(this.temp).then(response => {
                        this.$notify({
                          title: '成功',
                          message: '创建成功',
                          type: 'success',
                          duration: 2000
                        })
                        this.zTree = $.fn.zTree.getZTreeObj("treeDemo")
                        this.nodes = this.zTree.getSelectedNodes()
                        //将新增结点挂在左侧树上
                        this.zTree.addNodes(this.nodes[0], -1,  [{id: response.data.menu_id, name: response.data.menu_name, isParent:true}] , true)
                        //alert(this.nodes[0].children[this.nodes[0].children.length -1].name);
                        //this.zTree.selectnode(this.nodes[0].children[this.nodes[0].children.length -1],true, true);
                        //this.selectnode(response.data.menu_id)
                        this.selectnode(this.nodes[0].id);
                      })
                  }
              })

            }
            if(this.type=='update'){
                this.$refs['dataForm'].validate((valid) => {
                  if (valid) {
                    updateMenu(this.temp).then(() => {
                      this.$notify({
                        title: '成功',
                        message: '更新成功',
                        type: 'success',
                        duration: 2000
                      })
                      //handleFilter()
                    })
                  }
                })
            }
           
            this.refresh();
            this.menu_code_readonly = true;
            this.type = 'update';
        },
        doDeleteMenu(){
            this.$confirm('确定要删除该菜单吗?', 'Warning', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            })
            .then(async() => {
              await deleteMenu(this.temp.menu_id)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.refresh()
            })
            .catch(err => { console.error(err) })
        },
        setType(type){
          this.type = type;
          if(this.type=="add"){
            this.temp.menu_code_parent = this.menu_code_current;
            this.temp.menu_name_parent = this.menu_name_current;
            this.temp.menu_code = '';
            this.temp.menu_name = '';
            this.temp.menu_addr = '';
            this.menu_code_readonly = false;
            this.menu_name_readonly = false;
            //生成新组织机构编码
            this.genNewMenuno();
          }else if(this.type=="update"){
            this.menu_name_readonly = false;
            this.$refs['menu_name'].focus();
          }
        },
        genNewMenuno(){
            this.genCodeParam.menu_id_parent = this.temp.menu_id
            this.genCodeParam.menu_code_parent = this.temp.menu_code_parent
            genCode(this.genCodeParam).then(response => {
                this.temp.menu_code = response.data;
            })
        }

    }
    
}
</script>
<style lang="scss" scoped>
//用于调整form中的行间距，这个应该修改为全局变量吧！
.app-container {
  .el-form {
    .el-form-item {
      margin-bottom: 11px;
    }
  }
  .form-footer {
      margin-left: 50px;
    }
}
</style>


